# -*- coding: utf-8 -*-
#  ISO-8859-1 Characters to HTML Entities Plugin
# 
#  Copyright (C) 2011 Willian Gustavo Veiga <wiltave@gmail.com>
#   
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#   
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#   
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330,
#  Boston, MA 02111-1307, USA.

import gedit
import gtk
import pygtk
import os
import gettext
import re

ui_str = """<ui>
	<menubar name="MenuBar">
		<menu name="ToolsMenu" action="Tools">
			<placeholder name="ToolsOps_2">
				<menuitem name="Iso88591CharactersToHtmlEntities" action="Iso88591CharactersToHtmlEntities"/>
			</placeholder>
		</menu>
	</menubar>
</ui>
"""

TEXT_DOMAIN = 'iso88591characterstohtmlentities'
LOCALE_DIRECTORY = os.path.expanduser('~/.gnome2/gedit/plugins/locale/') #FIXME: Can I run it just from home?

gettext.bindtextdomain(TEXT_DOMAIN, LOCALE_DIRECTORY)
gettext.textdomain(TEXT_DOMAIN)
_ = gettext.gettext

class Iso88591CharactersToHtmlEntitiesPlugin(gedit.Plugin):
	def __init__(self):
		self.instances = {}

	def activate(self, window):
		self.instances[window] = Iso88591CharactersToHtmlEntitiesHelper(window)

	def deactivate(self, window):
		self.instances[window].deactivate()
		del self.instances[window]

	def update_ui(self, window):
		self.instances[window].update_ui()

class Iso88591CharactersToHtmlEntitiesHelper():
	def __init__(self, window):
		self.window = window
		self.action_group = None
		self.ui_id = 0

		self.insert_menu()

	def deactivate(self):
		self.remove_menu()

	def update_ui(self):
		self.action_group.set_sensitive(self.window.get_active_document() != None)

	def insert_menu(self):
		manager = self.window.get_ui_manager()

		self.action_group = gtk.ActionGroup("Iso88591CharactersToHtmlEntitiesPluginActions")
		self.action_group.add_actions([("Iso88591CharactersToHtmlEntities", None, _("ISO-8859-1 characters to HTML entities"), None, _("Convert ISO-8859-1 characters to HTML entities"), self.replace_characters)])

		manager.insert_action_group(self.action_group, -1)
		self.ui_id = manager.add_ui_from_string(ui_str)

	def remove_menu(self):
		manager = self.window.get_ui_manager()

		manager.remove_ui(self.ui_id)
		manager.remove_action_group(self.action_group)

		manager.ensure_update()

	def replace_characters(self, action):		
		doc = self.get_current_doc()

		old_text = self.get_full_document_text()

		characters = {'À': '&Agrave;', 'Á': '&Aacute;', 'Â': '&Acirc;', 'Ã': '&Atilde;', 'Ä': '&Auml;', 'Å': '&Aring;', 'Æ': '&AElig;', 'Ç': '&Ccedil;', 'È': '&Egrave;', 'É': '&Eacute;', 'Ê': '&Ecirc;', 'Ë': '&Euml;', 'Ì': '&Igrave;', 'Í': '&Iacute;', 'Î': '&Icirc;', 'Ï': '&Iuml;', 'Ð': '&ETH;', 'Ñ': '&Ntilde;', 'Ò': '&Ograve;', 'Ó': '&Oacute;', 'Ô': '&Ocirc;', 'Õ': '&Otilde;', 'Ö': '&Ouml;', 'Ø': '&Oslash;', 'Ù': '&Ugrave;', 'Ú': '&Uacute;', 'Û': '&Ucirc;', 'Ü': '&Uuml;', 'Ý': '&Yacute;', 'Þ': '&THORN;', 'ß': '&szlig;', 'à': '&agrave;', 'á': '&aacute;', 'â': '&acirc;', 'ã': '&atilde;', 'ä': '&auml;', 'å': '&aring;', 'æ': '&aelig;', 'ç': '&ccedil;', 'è': '&egrave;', 'é': '&eacute;', 'ê': '&ecirc;', 'ë': '&euml;', 'ì': '&igrave;', 'í': '&iacute;', 'î': '&icirc;', 'ï': '&iuml;', 'ð': '&eth;', 'ñ': '&ntilde;', 'ò': '&ograve;', 'ó': '&oacute;', 'ô': '&ocirc;', 'õ': '&otilde;', 'ö': '&ouml;', 'ø': '&oslash;', 'ù': '&ugrave;', 'ú': '&uacute;', 'û': '&ucirc;', 'ü': '&uuml;', 'ý': '&yacute;', 'þ': '&thorn;', 'ÿ': '&yuml;'}

		new_text = old_text
		number = 0

		for k, v in characters.iteritems():
			regular_expression = re.compile(k)
			result = regular_expression.subn(v, new_text)

			new_text = result[0]
			number += result[1]

		# insert new text
		if new_text != old_text:
			doc.begin_user_action()
			# clear text from current document
			doc.set_text('', 0)
			doc.insert_at_cursor(new_text)
			doc.end_user_action()
			self.set_statusbar_text(str(number) + _(' characters has been replaced.') if number != 1 else _('1 character has been replaced.'))
		else:
			self.set_statusbar_text(_("Nothing has been replaced."))

	def get_full_document_text(self):
		doc = self.get_current_doc()

		text = doc.get_text(doc.get_start_iter(), doc.get_end_iter())

		return text

	def get_current_doc(self):
		self.window = gedit.app_get_default().get_active_window()
		view = self.window.get_active_view()

		doc = view.get_buffer()

		return doc

	def set_statusbar_text(self, text):
		statusbar = self.window.get_statusbar()

		context_id = statusbar.get_context_id('GeditStatusBarIso88591CharactersToHtmlEntitiesPlugin')
		statusbar.flash_message(context_id, text)
